package cn.rick.controller;

import cn.dev33.satoken.util.SaResult;
import cn.rick.entity.BuildCategory;
import cn.rick.service.IBuildCategoryService;
import cn.rick.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 主材料分类 前端控制器
 * </p>
 *
 * @author house_store
 * @since 2022-10-29 14:46:14
 */
@RestController
@RequestMapping("/api/buildCategory")
@Api(value = "主材料分类", tags = {"主材料分类"})
public class BuildCategoryController {

    @Resource
    private IBuildCategoryService iBuildCategoryService;

    /**
     * 获取分类的全部数据
     *
     * @param buildCategory 实体为参
     * @return result
     */
    @GetMapping("/getData")
    @ApiOperation("获取分类数据")
    public SaResult getData(BuildCategory buildCategory) {
        LambdaQueryWrapper<BuildCategory> 条件 = new LambdaQueryWrapper<>();
        //通过排序号码进行顺序
        条件.orderByAsc(BuildCategory::getOrderNum);

        //如果分类名不为空，查询
        if (StringUtils.isNotEmpty(buildCategory.getName())) {
            条件.like(BuildCategory::getName, buildCategory.getName());
        }
        //如果分类状态不为空，查询
        if (StringUtils.isNotEmpty(buildCategory.getStatus())) {
            条件.eq(BuildCategory::getStatus, buildCategory.getStatus());
        }

        //查询
        List<BuildCategory> 得到的数据 = iBuildCategoryService.list(条件);

        //如果有查询参数，直接返回list, 如果是查询全部数据，则返回树形
        if (StringUtils.isNotEmpty(buildCategory.getName()) || "1".equals(buildCategory.getStatus())) {
            return SaResult.data(得到的数据);
        } else {
            return SaResult.data(category0(得到的数据));
        }
    }

    /**
     * 保存分类
     *
     * @param buildCategory 实体类
     * @return result
     */
    @PostMapping("/save")
    @ApiOperation("保存分类")
    public SaResult save(@RequestBody BuildCategory buildCategory) {
        LambdaQueryWrapper<BuildCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BuildCategory::getName, buildCategory.getName()).eq(BuildCategory::getParentId, buildCategory.getParentId());

        if (Objects.nonNull(iBuildCategoryService.getOne(queryWrapper))) {
            return SaResult.error("同级分类名称已存在");
        } else {
            //如果其父id为0，则设置祖籍列表为0
            if (buildCategory.getParentId() == 0) {
                buildCategory.setAncestors("0");
            } else {
                //否则以父级的祖籍列表拼接父级的id作为自己的祖籍列表
                BuildCategory byId = iBuildCategoryService.getById(buildCategory.getParentId());
                StringBuilder builder = new StringBuilder(byId.getAncestors());
                buildCategory.setAncestors(String.valueOf(builder.append(",").append(byId.getId())));
            }

            if (StringUtils.isNotNull(buildCategory.getId())) {
                buildCategory.setUpdateTime(LocalDateTime.now());
            }

            if (iBuildCategoryService.saveOrUpdate(buildCategory)) {
                return SaResult.ok("保存成功");
            } else {
                return SaResult.error("保存失败");
            }
        }
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation("删除分类")
    public SaResult del(@PathVariable Long id) {
        BuildCategory byId = iBuildCategoryService.getById(id);
        if (byId.getMaterialsCount() != 0) {
            return SaResult.error("此分类下还有主材料，不能删除");
        } else {
            LambdaQueryWrapper<BuildCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BuildCategory::getParentId, id);
            List<BuildCategory> list = iBuildCategoryService.list(queryWrapper);
            if (list.size() > 0) {
                return SaResult.error("删除失败，该分类下还有<" + list.size() + ">个子分类");
            } else {
                iBuildCategoryService.removeById(id);
                return SaResult.ok("删除成功");
            }
        }
    }

    /**
     * 循环添加子级
     *
     * @param sysMenus list
     * @return list
     */
    public List<BuildCategory> category0(List<BuildCategory> sysMenus) {
        List<BuildCategory> category0 = sysMenus.stream().filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());
        category0.forEach(category0Item -> {
            List<BuildCategory> category1 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category0Item.getId())).collect(Collectors.toList());
            category1.forEach(category1Item -> {
                List<BuildCategory> category2 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category1Item.getId())).collect(Collectors.toList());
                category2.forEach(category2Item -> {
                    List<BuildCategory> category3 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category2Item.getId())).collect(Collectors.toList());
                    category3.forEach(category3Item -> {
                        List<BuildCategory> category4 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category3Item.getId())).collect(Collectors.toList());
                        category3Item.setChildren(category4);
                    });
                    category2Item.setChildren(category3);
                });
                category1Item.setChildren(category2);
            });
            category0Item.setChildren(category1);
        });
        return category0;
    }

}
